package com.leyou.user.controller;

import com.leyou.common.exception.LyException;
import com.leyou.user.domain.User;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
@RequestMapping
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Void> registry(@Valid User user, BindingResult result, @RequestParam("code") String code){
        if (result.hasErrors()) {
            String error = result.getFieldErrors()
                    .stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400, error);
        }
        userService.registry(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    /**
     * 用户校验
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUsernameOrPhone(@PathVariable("data") String data,
                                                        @PathVariable("type") Integer type){
        Boolean result=userService.checkUsernameOrPhone(data,type);
        return ResponseEntity.ok(result);
    }

    /**
     * 发送验证码
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCheckCode(@RequestParam("phone") String phone){
        userService.sendCheckCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 判断用户名和密码是否正确
     */
    @GetMapping("/query")
    public ResponseEntity<UserDTO> findUsernameAndPassword(@RequestParam("username") String username,
                                                           @RequestParam("password") String password){
        UserDTO userDTO=userService.findUsernameAndPassword(username,password);
        return ResponseEntity.ok(userDTO);
    }
}
